package com.ws.strategy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Component
public class MessageHandlerFactory implements ApplicationContextAware {
    private static final HashMap<Integer, MessageHandler> messageHandlerFactory = new HashMap<>();


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, MessageHandler> messageHandlerMap = applicationContext.getBeansOfType(MessageHandler.class);
        messageHandlerMap.values().forEach(messageHandler -> {
            messageHandlerFactory.put(messageHandler.getMesType(), messageHandler);
        });
    }

    public boolean process(Integer type, String mesJson) {
        MessageHandler messageHandler = messageHandlerFactory.get(type);
        if (messageHandler!=null){
            messageHandler.handleMessage(mesJson);
            return true;
        }
        return false;
    }

}
